<?php
declare (strict_types=1);

namespace app\middleware;

use app\api\services\JwtService;
use app\api\traits\CommonTrait;

/**
 * Class CheckToken
 * @package app\middleware
 * @desc 校验token中间件
 */
class CheckToken
{
    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //获取header里传过来的token
        $token = $request->header('token');
        if (!$token) {
            return CommonTrait::returnJson(400, 'token不能为空');
        }
        $tokenRet = JwtService::verifyJwt($token);
        // 校验token不通过
        if ($tokenRet['code'] != 200) {
            return CommonTrait::returnJson($tokenRet['code'], $tokenRet['msg']);
        }
        $request->uid = $tokenRet['data'];
        return $next($request);
    }
}
